<%@ page language="java" contentType="application/javascript; charset=UTF-8"
	pageEncoding="UTF-8"%>
	<%@page import="dao.Products" %>
	<%@page import="model.ProductModel" %>
Ext.Loader.setConfig({
    enabled: true
});
Ext.Loader.setPath('Ext.ux', './ux');

Ext.require([
    'Ext.grid.*',
    'Ext.data.*',
    'Ext.util.*',
    'Ext.state.*',
    'Ext.form.*',
    'Ext.ux.CheckColumn'
]);

Ext.onReady(function(){
    // Define our data model
    Ext.define('Products', {
        extend: 'Ext.data.Model',
        fields: [
            'id',
            'name',
            'price',
            'quantities',
            'type_id',
            'event_id',
            'image_url',
            'date_expire'
        ]
    });

    // Generate mock data
    var data = (function() {
            data = [];
            <%
            	Products p = new Products();
            	for(ProductModel pm:p.ListProducts()){
            %>
                data.push({
                    id : '<%=pm.getId() %>',
                    name: '<%=pm.getName() %>',
                    price: <%=pm.getPrice() %>,
                    quantities: <%=pm.getQuantities() %>,
                    type_id: '<%=pm.getName() %>',
                    event_id: '<%=pm.getEvent_id() %>',
                    image_url: '<%=pm.getImage_url() %>',
                    date_expire: '<%=pm.getDate_expire()%>'
                });
            <%
            }
             %>   
        return data;
    })();

    // create the Data Store
    var store = Ext.create('Ext.data.Store', {
        // destroy the store if the grid is destroyed
        autoDestroy: true,
        model: 'Products',
        proxy: {
            type: 'memory'
        },
        data: data,
        sorters: [{
            property: 'start',
            direction: 'ASC'
        }]
    });

    var rowEditing = Ext.create('Ext.grid.plugin.RowEditing', {
        clicksToMoveEditor: 1,
        autoCancel: false,
        listeners: {
        	edit: function(editor, e, opts){
	        		Ext.Ajax.request({
					    url: 'CreateProducts',
					    method: 'post',
					    params: {
					    	id : e.record.get('id'),
		                    name: e.record.get('name'),
		                    price: e.record.get('price'),
		                    quantities: e.record.get('quantities'),
		                    type_id: e.record.get('type_id'),
		                    event_id: e.record.get('event_id'),
		                    image_url: e.record.get('image_url'),
		                    date_expire: e.record.get('date_expire')
					    },
					    success: function(response){
					        var text = response.responseText;
					        Ext.MessageBox.alert('Thông báo', text);
					    }
					});
        	}
        }  
    });
    // create the grid and specify what field you want
    // to use for the editor at each column.
    var grid = Ext.create('Ext.grid.Panel', {
        store: store,
        columns: [{
	            header: 'Mã sản phẩm',
	            dataIndex: 'id',
	            width: '12.5%',
	            flex: 1,
	            editor: {
	            	//disabled: true,
	                allowBlank: false
            	}
	        }, 
	        {
	            header: 'Tên sản phẩm',
	            dataIndex: 'name',
	            width: '12.5%',
	            editor: {
	                allowBlank: false,
	            }
	        }, 
        	{
	            header: 'Đơn giá',
	            dataIndex: 'price',
	            flex: 1,
	            width: '12.5%',
	            editor: {
	                		allowBlank: false,
	            		}
        	},
        	{
	            header: 'Số lượng',
	            dataIndex: 'quantities',
	            flex: 1,
	            width: '12.5%',
	            editor: {
	                		allowBlank: false,
	            		}
        	},
        	{
	            header: 'Mã loại',
	            dataIndex: 'type_id',
	            flex: 1,
	            width: '12.5%',
	            editor: {
	                		allowBlank: false,
	            		}
        	},
        	{
	            header: 'Mã sự kiện',
	            dataIndex: 'event_id',
	            flex: 1,
	            width: '12.5%',
	            editor: {
	                		allowBlank: false,
	            		}
        	},
        	{
	            header: 'Ngày hết hạn',
	            dataIndex: 'date_expire',
	            flex: 1,
	            width: '12.5%',
	            editor: {
                		allowBlank: false,
            		}
        	},
        	{
	            header: 'Hình ảnh',
	            dataIndex: 'image_url',
	            flex: 1,
	            width: '12.5%',
	            editor: {
                		allowBlank: false,
            		}
        	}//,
        	//{
		    //   header: 'Xóa/Sửa ảnh', 
		    //   flex: 1, 
		    //   sortable: false, 
		    //   renderer: function(val){ return '<input type="button" value="Sửa ảnh" id="'+val+'"/>'; }, 
		    //   dataIndex: 'id'
			//}
        ],
        renderTo: 'list-products',
        width: '100%',
        height: 400,
        title: 'SẢN PHẨM',
        iconCls: 'order',
        frame: true,
        tbar: [{
            text: 'Thêm',
            iconCls: 'order-add',
            handler : function() {
                rowEditing.cancelEdit();
                // Create a model instance
                var r = Ext.create('Products', {
                    id: '',
                    name: '',
                    price: 0,
                    quantities: 0,
                    type_id: '',
                    event_id: '',
                    image_url: '',
                    date_expire: ''
                });
                store.insert(0, r);
                rowEditing.startEdit(0, 0);
            }
        },
        {
            itemId: 'removeProduct',
            text: 'Xóa',
            iconCls: 'order-remove',
            handler: function() {
            	Ext.MessageBox.confirm('Xác nhận', 'Bạn có muốn xóa sản phẩm này không?', function(btn){
            		if(btn == "yes"){
		                var sm = grid.getSelectionModel();
		                rowEditing.cancelEdit();
		                //[0] là dòng, [1] là cột
						var Id = sm.getSelection()[0].get('id');
		                store.remove(sm.getSelection());
		                if (store.getCount() > 0) {
		                	Ext.Ajax.request({
							    url: 'DeleteProduct',
							    method: 'get',
							    params: {
							        id: Id,
							    },
							    success: function(response){
							        var text = response.responseText;
							        Ext.MessageBox.alert('Thông báo', text);
							    }
							});
		                	sm.select(0);
		                }
		             }
            	});
            },
            disabled: true
        },
        {
        	itemId: 'editProduct',
            text: 'Up Anh',
            iconCls: 'order-remove',
            handler: function() {
            	var sm = grid.getSelectionModel();
		        //[0] là dòng, [1] là cột
				var Id = sm.getSelection()[0].get('id');
            	new Ext.Window({
	            	title: 'Up ảnh',
	                closable: true,
	                closeAction: 'hide',
	                width: 400,
	                height: 250,
	                y: 100,
                	resizable: true,
                	layout: {
	                    type: 'anchor',
	                    padding: 5,
                	},
	                html: '<iframe src="./uploadImage.jsp?id=' + Id + '" scrolling="yes" frameborder="0" width="400" height="400"></iframe>'
				}).show();
            },
            disabled: true
        }], 
        plugins: [rowEditing],
        listeners: {
            'selectionchange': function(view, records) {
                grid.down('#removeProduct').setDisabled(!records.length);
                grid.down('#editProduct').setDisabled(!records.length);
            }
        }
    });
});
